package com.xdl.configuration;

import com.xdl.common.jwt.IJWTInfo;
import com.xdl.common.jwt.JWTHelper;
import com.xdl.common.utils.StringUtils;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;


/**
 * @ClassName TransmitUserInfoFilter
 * @Description TODO
 * @Author iron
 * @Date 2020/8/31 13:50
 * @Version 1.0
 */
@Slf4j
@Configuration
public class TransmitUserInfoFilter implements Filter {

    public TransmitUserInfoFilter() {
    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }

    @SneakyThrows
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain){
            this.initUserInfo((HttpServletRequest) request);
            chain.doFilter(request, response);
    }

    private void initUserInfo(HttpServletRequest request) throws Exception {
        String token = request.getHeader("X-Access-Token");
        if(StringUtils.isNotBlank(token) && JWTHelper.verify(token)){
            IJWTInfo jwt = JWTHelper.getInfoFromToken(token);
            BaseContextHandler.setUsername(jwt.getUserName());
            BaseContextHandler.setUserID(jwt.getUserId());
            BaseContextHandler.setPhone(jwt.getPhone());
        }else {
            BaseContextHandler.remove();
        }
    }

    @Override
    public void destroy() {
    }

}
